package com.sml.service.impl;

import com.sml.mapper.UserMapper;
import com.sml.pojo.User;
import com.sml.service.UserService;
import com.sml.utils.MD5Util;
import com.sml.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public void register(String username, String password) {
        //密码加密
        String md5String = MD5Util.getMD5String(password);
        //添加到数据库
        userMapper.add(username, md5String);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        //获取拦截器中的用户id
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        userMapper.updateAvatar(avatarUrl,id);
    }

    /**
     * 修改密码
     * @param newPwd 新密码
     */
    @Override
    public void updatePwd(String newPwd) {
        //获取拦截器中的用户id
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        userMapper.updatePwd(MD5Util.getMD5String(newPwd),id);
    }
}
